package com.media.selector.media.model

import android.content.ContextWrapper
import android.database.Cursor
import android.os.Bundle
import androidx.annotation.NonNull
import androidx.annotation.Nullable
import androidx.fragment.app.FragmentActivity
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import com.media.selector.media.model.entity.AlbumEntity
import com.media.selector.media.model.loader.AlbumMediaLoader

/**
 * date        ：2020/5/11
 * author      ：蒙景博
 * description ：
 */
class AlbumMediaCollection constructor(activity: FragmentActivity): ContextWrapper(activity), LoaderManager.LoaderCallbacks<Cursor> {

    companion object {
        private const val LOADER_ID = 2
        const val ARGS_ALBUM = "args_album"
        const val ARGS_ENABLE_CAPTURE = "args_enable_capture"
    }

    private var mLoaderManager: LoaderManager? = null
    private var mCallbacks: AlbumMediaCallbacks?= null

    init {
        mLoaderManager = LoaderManager.getInstance(activity)
    }

    fun onCreate(@NonNull callbacks: AlbumMediaCallbacks) {
        mCallbacks = callbacks
    }

    fun onDestroy() {
        mLoaderManager?.destroyLoader(LOADER_ID)
        mCallbacks = null
    }

    fun loadMedia(@Nullable target: AlbumEntity?) {
        mLoaderManager?.restartLoader(LOADER_ID, Bundle().apply {
            putParcelable(ARGS_ALBUM, target)
            putBoolean(ARGS_ENABLE_CAPTURE, SelectionSpec.with().capture)
        }, this)
    }

    override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> {
        val album = args?.getParcelable<AlbumEntity>(ARGS_ALBUM)!!
        val isCapture = args.getBoolean(ARGS_ENABLE_CAPTURE, false)
        return AlbumMediaLoader.with(this, album.mId, album.isAll(), isCapture)
    }

    override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) {
        mCallbacks?.onAlbumMediaLoad(data)
    }

    override fun onLoaderReset(loader: Loader<Cursor>) {
        mCallbacks?.onAlbumMediaReset()
    }

    interface AlbumMediaCallbacks {
        fun onAlbumMediaLoad(cursor: Cursor?)
        fun onAlbumMediaReset()
    }
}